<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    okText="提交"
    @register="register"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #slotVariable="{ model, field }">
          <checkTable
            :value="model[field]"
            title="选择设备信息"
            :isShowSearch="true"
            :columnsProps="columnsPropsByDrive"
            :tableParams="tableParamsByDrive"
            :isErroByVariable="isErroByDrive"
            @check-tag="handleCheckByDrive"
          />
        </template>
        <template #slotByStorage="{ model, field }">
          <checkTable
            :value="model[field]"
            title="选择存储信息"
            :columnsProps="columnsPropsByStorage"
            :tableParams="tableParamsByStorage"
            labelName="Name"
            :isMultiple="true"
            :isShowSearch="true"
            :isErroByVariable="isErroByStorage"
            @check-tag="handleCheckTag"
          />
        </template>
        <template #slotByCondition="{ model, field }">
          <checkTable
            :value="model[field]"
            title="选择触发条件"
            :isShowSearch="true"
            :columnsProps="columnsPropsByCondition"
            :tableParams="tableParamsByCondition"
            :isErroByVariable="isErroByCondition"
            @check-tag="handleCheckByCondition"
          />
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { checkName } from '/@/utils/index';
  import checkTable from '/@/components/selectTable/index.vue';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { gettags, getdrivers } from '/@/api/hda/index';
  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  // 触发条件信息
  let conditionInfo = {};
  let typeObj = {
    0: 'None',
    1: 'BOOL',
    2: 'LittleEndian',
    3: 'BYTE',
    4: 'SHORT',
    5: 'WORD',
    6: 'DWORD',
    7: 'INT',
    8: 'FLOAT',
    11: 'STR',
    12: 'DYNAMIC',
  };
  let isErroByDrive = ref<boolean>(false);
  let isErroByStorage = ref<boolean>(false);
  let isErroByCondition = ref<boolean>(false);
  let columnsPropsByStorage: BasicColumn[] = [
    {
      title: '标签名',
      dataIndex: 'Name',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editComponent: 'Input',
      width: 120,
    },
    {
      title: '全称',
      dataIndex: 'Key',
    },
    {
      title: '索引',
      dataIndex: 'IsIndex',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editComponent: 'Switch',
      width: 80,
    },
    {
      title: '地址',
      dataIndex: 'Addr',
    },
    {
      title: '数据类型',
      dataIndex: 'VarTypeCn',
    },
  ];
  let columnsPropsByCondition: BasicColumn[] = [
    {
      title: '标签名',
      dataIndex: 'Name',
    },
    {
      title: '全称',
      dataIndex: 'Key',
    },
    {
      title: '地址',
      dataIndex: 'Addr',
    },
    {
      title: '数据类型',
      dataIndex: 'VarTypeCn',
    },
  ];
  let columnsPropsByDrive: BasicColumn[] = [
    {
      title: '设备名称',
      dataIndex: 'DriverName',
    },
    {
      title: '设备全称',
      dataIndex: 'DriverFullName',
    },
  ];
  let tableParamsByDrive = {
    api: getdrivers,
    rowKey: 'DriverFullName',
  };

  let tableParamsByStorage = {
    api: gettags,
    rowKey: 'Key',
    clickToRowSelect: false,
    afterFetch: (v) => {
      return v.map((item) => {
        item.Addr = item.Address.Addr;
        item.IsIndex = false;
        item.VarTypeCn = typeObj[item.Address.VarType];
        return item;
      });
    },
    params: {
      driverFullName: '',
    },
  };
  let tableParamsByCondition = {
    api: gettags,
    rowKey: 'Key',
    afterFetch: (v) => {
      return v.map((item) => {
        item.Addr = item.Address.Addr;
        item.VarTypeCn = typeObj[item.Address.VarType];
        return item;
      });
    },
    params: {
      driverFullName: '',
    },
  };
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新增' : '编辑'}`;
  });

  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'Name',
      component: 'Input',
      label: '名称：',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, `名称`),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'DeviceName',
      component: 'Input',
      label: '设备：',
      slot: 'slotVariable',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请选择设备',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'AssetCode',
      component: 'Input',
      label: '设备编码：',
      ifShow: ({ values }) => {
        return [null, '', undefined].indexOf(values.DeviceName) === -1;
      },
      colProps: {
        span: 24,
      },
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'DeviceFullName',
      component: 'Input',
      label: '设备全称：',
      ifShow: ({ values }) => {
        return [null, '', undefined].indexOf(values.DeviceName) === -1;
      },
      componentProps: {
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },

    {
      field: 'TagFullName',
      component: 'Input',
      label: '存储信息：',
      slot: 'slotByStorage',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (!value || value.length === 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择设备参数');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ConditionName',
      component: 'Input',
      label: '触发条件：',
      slot: 'slotByCondition',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请选择触发条件',
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];

  const [registerForm, { validateFields, resetFields, clearValidate, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();

  async function handleSubmint() {
    try {
      let res = await validateFields();
      let baseParams = {
        GroupName: props.info.data.serverName,
        DeviceName: res.DeviceName,
        DeviceFullName: res.DeviceFullName,
        AssetCode: res.AssetCode,
        RelationItemName: res.Name,
        OldRelationItemName: res.Name,
        TagFullName: res.TagFullName.map((item) => {
          return {
            Name: item.Name,
            FullName: item.Key,
            DataType: item.VarTypeCn,
            Value: item.Value,
            IsIndex: item.IsIndex,
          };
        }),
        Condition: {
          Name: conditionInfo.Name,
          FullName: conditionInfo.Key,
          DataType: conditionInfo.VarTypeCn,
          Value: conditionInfo.Value,
        },
      };
      if (props.info.type === 'add') {
        // props.info.data.Key,
        await props.info.addApi([baseParams]);
      } else {
        (baseParams.OldRelationItemName = props.info.data.RelationItemName),
          await props.info.editApi([baseParams]);
      }

      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      isErroByDrive.value = ['', null, undefined].indexOf(error.values.DeviceName) >= 0;
      isErroByStorage.value = !error.values.TagFullName || error.values.TagFullName.length === 0;
      isErroByCondition.value = ['', null, undefined].indexOf(error.values.ConditionName) >= 0;
      console.log('not passing', error);
    }
  }
  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(() => {
        let { Condition, TagFullName, DeviceFullName, DeviceName, AssetCode, RelationItemName } =
          props.info.data;
        if (props.info.type === 'update') {
          conditionInfo = {
            Name: Condition.Name,
            Key: Condition.FullName,
            VarTypeCn: Condition.DataType,
            Value: Condition.Value,
          };
          setFieldsValue({
            ConditionName: Condition.Name,
            TagFullName: TagFullName.map((item) => {
              return {
                Name: item.Name,
                Key: item.FullName,
                VarTypeCn: item.DataType,
                Value: item.Value,
                IsIndex: item.IsIndex,
              };
            }),
            DeviceFullName,
            DeviceName,
            AssetCode,
            Name: RelationItemName,
          });
          tableParamsByStorage.params.driverFullName = DeviceFullName;
          tableParamsByCondition.params.driverFullName = DeviceFullName;
        }
        clearValidate();
      });
    } else {
      isErroByStorage.value = false;
      isErroByCondition.value = false;
      isErroByDrive.value = false;
      tableParamsByStorage.params.driverFullName = '';
      tableParamsByCondition.params.driverFullName = '';
      resetFields();
    }
  }
  // 触发条件选择事件
  function handleCheckByCondition(val) {
    let resList = val.val;
    let targetInfo = Array.isArray(resList) && resList.length > 0 ? resList[0] : {};
    conditionInfo = targetInfo;
    setFieldsValue({
      ConditionName: targetInfo.Name,
    });
    isErroByCondition.value = false;
  }
  // 设备选择事件
  function handleCheckByDrive(val) {
    let resList = val.val;
    let targetInfo = Array.isArray(resList) && resList.length > 0 ? resList[0] : {};
    setFieldsValue({
      DeviceName: targetInfo.DriverName,
      DeviceFullName: targetInfo.DriverFullName,
      AssetCode: targetInfo.DriverNO,
      PDU: targetInfo.PDU,
    });
    tableParamsByStorage.params.driverFullName = targetInfo.DriverFullName;
    tableParamsByCondition.params.driverFullName = targetInfo.DriverFullName;
    isErroByDrive.value = false;
  }
  function handleCheckTag(val) {
    let resList = val.val;
    setFieldsValue({
      TagFullName: resList,
    });

    isErroByStorage.value = false;
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
</style>
